//
//  ServiceTheHallViewControl.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/9.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "ServiceTheHallViewControl.h"
#import "ServiceTheHallHeaderView.h"
#import "ServiceCollectionCell.h"
#import "ReleaseModel.h"
#import "ServiceTheHallHeaderView.h"
#import "ServiceContentTabVC.h"
#import "DemandAndServiceSearchView.h"
#import "NearHistoryView.h"
#import "ServiceModel.h"
#import "DemandAndServiceSearchTabVC.h"
@interface ServiceTheHallViewControl ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ServiceTheHallHeaderViewDelegate,ServiceCollectionCellDelegate,NearHistoryViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) UICollectionViewFlowLayout *flow;
@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) ServiceTheHallHeaderView *headerView;
@property(nonatomic,strong) NSMutableArray *titles;
@property(nonatomic,strong) ReleaseModel *model;
@property(nonatomic,strong) NSDictionary  *dict;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NearHistoryView *nearHisView;
@property(nonatomic,strong) NSMutableArray *historyMuta;
@end
static NSString *identifier = @"cell";
@implementation ServiceTheHallViewControl
-(NSMutableArray *)titles
{
    if (!_titles) {
        _titles = [NSMutableArray array];
    }
    return _titles;
}
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        self.flow = [[UICollectionViewFlowLayout alloc]init];
        self.flow.minimumLineSpacing = 0;
        self.flow.minimumInteritemSpacing = 0;
        self.flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.headerView.frame.size.height, kVWidth, kVHeight-self.headerView.frame.size.height-(kNavAndStatusHight)) collectionViewLayout:self.flow];
         _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.headerView.frame.size.height, kVWidth, kVHeight-self.headerView.frame.size.height-kNavAndStatusHight-kTabBarHeight) collectionViewLayout:self.flow];
        _collectionView.backgroundColor = kBg;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.model = [[ReleaseModel alloc]init];
    self.manager = [AFHTTPSessionManager manager];
    DemandAndServiceSearchView *searchView = [[DemandAndServiceSearchView alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.bounds.size.width, self.navigationController.navigationBar.bounds.size.height-8)];
    __weak typeof (self)weakSelf = self;
    searchView.returnValueBlock = ^(NSInteger selected) {
        if (selected == 0) {
            XLog(@"returnValueBlock");
            self.nearHisView = [[NearHistoryView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kUIScreen.size.height)];
            self.nearHisView.index = 2;
            self.nearHisView.show = YES;
            self.nearHisView.delegate = self;
            [weakSelf.view.superview.window addSubview:self.nearHisView];
            
        }else {
            DemandAndServiceSearchTabVC *vc = [[DemandAndServiceSearchTabVC alloc]init];
            vc.searchIndex = 2;
            [self.navigationController pushViewController:vc animated:YES];
        }
    };
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchView];
    self.headerView = [[ServiceTheHallHeaderView alloc]initWithFrame:CGRectMake(0, 0, kUIScreen.size.width, 100)];
    self.headerView.delegate = self;
    self.headerView.kNavHeight = kNavAndStatusHight+kStatusBarHeight*2;
    XLog(@"heght:%ld",(long)self.headerView.kNavHeight);
    XLog(@"heght:%f",kNavAndStatusHight);
    XLog(@"heght:%f",kStatusBarHeight);
    [self.view addSubview:self.headerView];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[ServiceCollectionCell class] forCellWithReuseIdentifier:identifier];
    [self.view addSubview:self.collectionView];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(historyinsertAssociation:) name:@"historyinsertAssociation" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInternet:) name:@"changeInternet" object:nil];
    [self reloadInternetData];
}
-(void)changeInternet:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    XLog(@"ServiceTheHallViewControlqingqiusibai:%@",dict);
    [self reloadInternetData];
    
}
//-(void)qingqiusibai:(NSNotification *)info
//{
//
//    XLog(@"ServiceTheHallViewControlqingqiusibai");
//}
#pragma mark-历史记录---跳转到详情
- (void)nearHistoryView:(NearHistoryView *)nearHistoryView withHidden:(BOOL)hidden withIndex:(NSInteger)index withServiceModel:(nonnull ServiceModel *)serviceModel
{
    [nearHistoryView removeFromSuperview];
    ServiceContentTabVC *vc = [[ServiceContentTabVC alloc]init];
    vc.model = serviceModel;
    [nearHistoryView removeFromSuperview];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)nearHistoryView:(NearHistoryView *)nearHistoryView withHidden:(BOOL)hidden
{
    [nearHistoryView removeFromSuperview];
}
-(void)reloadInternet
{
    
}
#pragma mark-初始化搜索
-(void)reloadInternetData
{
    self.titles = nil;
    self.urlString = [NSString stringWithFormat:@"%@/associationType/list",kUrl];
    [self.manager POST:self.urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //    XLog(@"dict:%@",dict);
        NSArray *date = [responseObject objectForKey:@"date"];
        for (NSDictionary *dict in date) {
            self.model = [ReleaseModel mj_objectWithKeyValues:dict];
            [self.titles addObject:self.model];
        };
        XLog(@"self.titles:%ld",self.titles.count);
        self.headerView.titles = self.titles;
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        self.collectionView.emptyDataSetSource = self;
        self.collectionView.emptyDataSetDelegate = self;
        [self.collectionView reloadData];
        [WSProgressHUD dismiss];
    }];
    
}
#pragma mark-代理:大类
-(void)serviceTheHallHeaderView:(ServiceTheHallHeaderView *)serviceTheHallHeaderView withTitleBtn:(nonnull MCButton *)mcBtn withAssModel:(nonnull ReleaseModel *)assModel
{
//        [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//        [WSProgressHUD show];
    
    [self.collectionView setContentOffset:CGPointMake((mcBtn.tag-1)*kVWidth, 0) animated:NO];
//    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:mcBtn.tag-1 inSection:0];
//    ServiceCollectionCell *cell = (ServiceCollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    cell.assModel = assModel;
//    [self.collectionView setContentOffset:CGPointMake((mcBtn.tag-1)*kVWidth, 0) animated:NO];
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/kVWidth;
    MCButton *mcBtn = (MCButton *)[self.headerView.titleScrollView viewWithTag:index+1];
    [self.headerView clickBtn:mcBtn];
    
//    XLog(@"index:%ld",index);
}
-(void)qingqiulist:(NSNotification *)info
{
    
    
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ServiceCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    ReleaseModel *model = self.titles[indexPath.row];
    cell.assModel = model;
    cell.delegate = self;
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kVWidth, kVHeight);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    //    if (section == 0) {
    return CGSizeMake(0, 0);
    //    }else {
    //        return CGSizeMake(200, 0);
    //    }
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //    if(section == 1){
    //        return UIEdgeInsetsMake(0, 0, 0.5, 0);//分别为上、左、下、右
    //    }else{
    return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
    //    }
    
}
#pragma mark-代理:跳转服务详情
-(void)serviceCollectionCell:(ServiceCollectionCell *)serviceCollectionCell withModel:(ServiceModel *)model
{
    
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken],
                  @"aids":[NumberSwitchString numberSwitchString:model.id]
                  };
    XLog(@"dict:%@",self.dict);
    self.urlString = [NSString stringWithFormat:@"%@/history/insertAssociation",kUrl];
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
        if (status == 200) {
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
    }];
    ServiceContentTabVC *vc = [[ServiceContentTabVC alloc]init];
    XLog(@"model.uid:%ld",model.uid);
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

//-(void)historyinsertAssociation:(NSNotification *)info
//{
//    NSDictionary *dict = info.userInfo;
//    XLog(@"dict:%@",dict);
//
//}
//-(void)dealloc
//{
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"nonetwork"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"请在iPhone的设置-无线局域网中允许商集使用WLAN与蜂窝移动网的应用";
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    // 设置所有字体大小为 #15
    [attStr addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:15.0]
                   range:NSMakeRange(0, text.length)];
    // 设置所有字体颜色为浅灰色
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:[UIColor lightGrayColor]
                   range:NSMakeRange(0, text.length)];
    // 设置指定4个字体为蓝色
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:[UIColor colorWithRed:47/255.0 green:119/255.0 blue:246/255.0 alpha:1]
                   range:NSMakeRange(9, 2)];
    [attStr addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:18.0]
                   range:NSMakeRange(9, 2)];
    return attStr;
}
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView
{
    NSString * urlString = UIApplicationOpenSettingsURLString;
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }
    }
}
@end
